package com.itheima.datastructure.stack;

import java.util.Iterator;

/**
 * @author tantao
 * @version 1.0
 * @description: 单向链表实现栈
 * @date 2025/9/15 10:20
 */
public class LinkedListStack01<E> implements Stack<E>, Iterable<E> {

    private final int capacity;
    private int size;
    private Node<E> head = new Node<>(null, null);//哨兵

    public LinkedListStack01(int capacity) {
        this.capacity = capacity;
    }

    //压栈
    @Override
    public boolean push(E value) {
        if (isFull()) {
            return false;
        }
        //详细：相当于在head和next中插入一个added
        //前：head -> next
        //后：head -> added -> next
//        Node<E> next = head.next;
//        Node<E> added = new Node<>(value, next);
//        head.next = added;
//        size++;

        head.next = new Node<>(value, head.next);
        size++;
        return true;
    }

    @Override
    public E pop() {
        if (isEmpty()) {
            return null;
        }
        //详细：移除first
        //head -> first ->nnext
        //head -> nnext
        Node<E> first = head.next;
        head.next = first.next;
        size--;
        return first.value;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return head.next.value;
    }

    @Override
    public boolean isEmpty() {
//        return head.next == null;
        //或
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public Iterator<E> iterator() {


        return new Iterator<E>() {
            Node<E> ptr = head.next;

            @Override
            public boolean hasNext() {
                return ptr != null;
            }

            //返回当前节点的值，并将ptr移到下一个节点
            @Override
            public E next() {
                E value = ptr.value;
                ptr = ptr.next;
                return value;
            }
        };
    }

    static class Node<E> {
        E value;
        Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }
}
